var app = getApp()

Page({
  data: {
    canvas: null,
    context: null,
    signNameUrl: '', //签名
    imgFlag: false, //完成签名
    // 前一点
    preX: 0,
    preY: 0
  },

  onShow: function () {
    const that = this;

    // 获取画布
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')

        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)

        // 设置笔触信息
        ctx.strokeStyle = '#000000'
        ctx.lineWidth = 2
        ctx.font = "20px Arial"

        that.setData({
          canvas: canvas,
          context: ctx
        })
      })
  },

  /**记录开始点 */
  bindtouchstart: function (e) {
    let context = this.data.context
    let curX = e.changedTouches[0].x
    let curY = e.changedTouches[0].y

    context.beginPath()
    context.moveTo(curX, curY)

    this.data.preX = curX
    this.data.preY = curY
  },

  /**记录移动点，刷新绘制 */
  bindtouchmove: function (e) {
    let context = this.data.context
    let preX = this.data.preX
    let preY = this.data.preY
    let curX = e.changedTouches[0].x
    let curY = e.changedTouches[0].y

    let deltaX = Math.abs(preX - curX)
    let deltaY = Math.abs(preY - curY)

    // 相差大于3像素的时候作二阶贝塞尔曲线
    if (deltaX >= 3 || deltaY >= 3) {
      // 前后两点中心点
      let centerX = (preX + curX) / 2
      let centerY = (preY + curY) / 2

      //这里以前一点作为控制点，中心点作为终点，起始点为上一次的中点，很流畅啊！
      context.quadraticCurveTo(preX, preY, centerX, centerY);
      context.stroke();

      this.data.preX = curX
      this.data.preY = curY
    }
  },

  /**清空画布 */
  clear: function () {
    let context = this.data.context
    let canvas = this.data.canvas

    context.clearRect(0, 0, canvas.width, canvas.height);

    context.strokeStyle = '#000000'
    context.lineWidth = 2
    context.font = "20px Arial"
  },

  /**导出图片 */
  export: function () {
    const that = this;
    wx.showLoading({
      title: '正在生成签名...',
    })
    wx.canvasToTempFilePath({
      canvas: that.data.canvas,
      success(res) {
        wx.hideLoading()
        console.log("tempFilePath:" + res.tempFilePath);
        that.setData({
          signNameUrl: res.tempFilePath,
          imgFlag: true
        })
      },
      fail() {
        wx.hideLoading()
        wx.showToast({
          title: '生成图片失败',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },
})